package com.ma.dp.demo;

/**
 * @ClassName FibTest
 * @Author: mayongqiang
 * @DATE 2022/3/29 11:19
 * @Description:
 */
public class FibTest {

    public static void main(String[] args) {
        System.out.println(dpFibSimple(10));

    }

    //带备忘录的解法
    public static int fib(int n) {
        if (n < 1) {
            return 0;
        }
        int[] memo = new int[n + 1];
        return helper(memo, n);
    }

    public static int helper(int[] memo, int n) {
        //base case
        if (n == 1 || n == 2) {
            return 1;
        }
        if (memo[n] != 0) {
            return memo[n];
        }
        memo[n] = helper(memo, n - 1) + helper(memo, n - 2);
        return memo[n];
    }

    // 自底向上的备忘录
    public static int dpFib(int n) {
        int[] dp = new int[n + 1];
        dp[1] = 1;
        dp[2] = 1;
        // 状态转移方程
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }

    // 优化空间复杂度
    public static int dpFibSimple(int n) {
        if (n == 1 || n == 2) {
            return 1;
        }
        int pre = 1, cur = 1;
        for (int i = 3; i <= n; i++) {
            int sum = pre + cur;
            pre = cur;
            cur = sum;
        }
        return cur;
    }
}
